<!--
 * @Author: your name
 * @Date: 2021-09-14 17:23:44
 * @LastEditTime: 2021-09-15 20:16:42
 * @LastEditors: Please set LastEditors
 * @Description: {{$st('wp_New_Repair')}}
 * @FilePath: \weplus_weibao_app\src\components\repairreport\CreateRepairOrder.vue
-->
<template>
    <div class="repair-container">
        <div class="repair-info-container">
            <wp-form-group
                ref="repairpublicformgoup"
                :formTitle="$st('wp_Repair_request_Information')"
                :formProp="repairprop"
                :groupRules="grouprules"
                v-model="repairForm.repairdata">
                <template #titleButton>
                    <div class="create-title-button-row">
                        <van-button
                            icon="search"
                            class="scan-button"
                            @click="reportQuery">{{$st('wp_Repair_Inquiry')}}</van-button>
                        <van-button
                            icon="scan"
                            class="scan-button"
                            @click="scanQrcode">{{$st('wp_Scan_the_QR_code_to_report_for_repair_quickly')}}</van-button>
                    </div>
                </template>
                <template #content>
                    <div class="tworow-field">
                        <van-field
                            :placeholder="$st('wp_Please_write_down_your_question_within_200_words')"
                            v-model="repairForm.repairdata.content"
                            :rules="grouprules.content"
                            type="textarea"
                            label-width="100%"
                            maxlength="200"
                            show-word-limit
                            autosize>
                            <template #label>
                                <span class="red">*</span>
                                <span>{{$st('wp_Problem_Description')}}</span>
                            </template>
                        </van-field>
                        <van-divider style="margin:0px 15px"/>
                    </div>
                </template>
                <template #attachments>
                    <div class="create-attachments-orderfile-container">
                        <label class="attachments-info-label">{{ $st('wp-fu-jian-xin-xi') }}</label>
                        <label
                            class="attachments-label"
                            :style="{float:'left'}">{{$st('wp_Photos_of_the_whole_machine_and_fault_points,_processing_files,_etc.,_upload_attachments_within_50MB')}}</label>
                        <order-file-uploader
                            v-model:attachments="repairForm.repairdata.attachments"/>
                    </div>
                </template>
            </wp-form-group>
            <wp-form-group
                ref="customerpublicformgoup"
                :formTitle="$st('wp_Customer_Information')"
                v-model="repairForm.repairdata"
                :groupRules="grouprules"
                :formProp="customerprop">
            </wp-form-group>
            <wp-form-group
                ref="devicepublicformgoup"
                :formTitle="$st('wp_Equipment_Information')"
                v-model="repairForm.repairdata"
                :groupRules="grouprules"
                :formProp="equipmentprop">
            </wp-form-group>
            <wp-form-group
                v-show="!isOrdinary"
                ref="principalpublicformgoup"
                :formTitle="$st('wp-gong-dan-fu-ze-ren')"
                v-model="repairForm.repairdata"
                :groupRules="grouprules"
                :formProp="principalprop">
            </wp-form-group>
            <wp-form-group
                :formTitle="$st('wp_Privacy_settings')"
                v-model="repairForm.repairdata"
                :groupRules="grouprules"
                :formProp="privacyprop">
                <template #allowviewbymanucode>
                    <div class="checkbox-cell">
                        <van-checkbox v-model="repairForm.repairdata.allowviewbymanucode"/>
                        <label class="allowviewbymanucode-label">
                            <span class="red">*</span>
                            <span>{{$st('wp_Allow_to_query_this_repair_request_via_factory_number_of_this_equipment')}}</span></label>
                    </div>
                </template>
            </wp-form-group>
        </div>
        <div class="button-div-fixed">
            <van-button
                class="submit-button"
                @click="submitReport">{{$st('wp_submit')}}</van-button>
        </div>
    </div>
</template>
<script>
import OrderFileUploader from '@/components/maintenance_control/repairreport/repaircommon/OrderFileUploader.vue';
import WpFormGroup from '@/components/_wp_components/WpFormGroup.vue';
import { reactive, onBeforeMount, onMounted, toRefs, watch } from 'vue';
import { useRoute } from 'vue-router';
import Cookies from 'js-cookie';
import { useRepairOrderQuerySetup } from '@/setup/repair/RepairReortQuerySetup.js';
import { getRepairDataSetup } from '@/setup/repair/RepairOrderDataSetup.js';
import { useProductArchiveDevicesSetup } from '@/setup/productarchive/ProductArchiveDevicesSetup.js';
import { selfI18n } from '@/i18n';
import RegConfig from '@/util/RegConfig';
import { useStore } from 'vuex';
import { showError } from '@/util/MessageDeal.js';
import useMaintenanceMembersSetup from '@/setup/maintenanceteam/MaintenanceTeamMembersSetup';
import useCustomerManageSetup from '@/setup/workbench/CustomerManageSetup.js';
import useMaintenanceInfoSetup from '@/setup/maintenanceteam/MaintenanceCustomInfoSetup';

export default {
    components: { OrderFileUploader, WpFormGroup },
    setup (props) {
        const route = useRoute();
        const manucode = route.query.manufacturecode;
        const { getAllMaintenanceTeamMembers } = useMaintenanceMembersSetup();
        const { queryCustomerRecorf } = useMaintenanceInfoSetup();
        const { getCustomrecordOne } = useCustomerManageSetup();

        const store = useStore();
        const userinfo = store.state.userinfo;
        const isOrdinary = !(userinfo && userinfo.roles && userinfo.roles.length > 0);
        const customer_id = route.params.customer_id;

        const validatorPhone = (value) => {
            if (value && !RegConfig.phone_number.test(value)) {
                return false;
            }
            return true;
        };
        const validatorEmail = (value) => {
            return !value || RegConfig.email.test(value);
        };

        const state = reactive({
            customerList: [],
            memberList: [],
            // 保修信息列设置
            repairprop: [
                {
                    id: 'content',
                    label: selfI18n('wp_Problem_Description'),
                    isrequired: true,
                    size: 'large',
                    placeholder: '200' + selfI18n('wp_Within_the_word')
                },
                {
                    id: 'attachments',
                    label: selfI18n('wp_Appendix'),
                    size: 'large'
                }
            ],
            // 工单负责人
            principalprop: [
                {
                    id: 'administrator',
                    label: selfI18n('wp-zhang-hao'),
                    placeholder: selfI18n('wp-qing-xuan-ze-gong-dan-fu-ze-ren'),
                    formtype: 'selectfield',
                    columns: []
                },
                {
                    id: 'principalphone',
                    label: selfI18n('wp-shou-ji-hao'),
                    placeholder: selfI18n('wp-qing-shu-ru-shou-ji-hao'),
                    name: 'validatorPhone',
                    disabled: true
                }
            ],
            // 客户信息列设置
            customerprop: [
                {
                    id: 'name',
                    label: selfI18n('wp-bao-xiu-ren'),
                    isrequired: true,
                    placeholder: selfI18n('wp_Please_fill_in_your_name')
                },
                {
                    id: 'phone',
                    label: selfI18n('wp-shou-ji-hao'),
                    isrequired: true,
                    placeholder: selfI18n('wp_Please_fill_in_the_correct_mobile_number'),
                    name: 'validatorPhone'
                },
                {
                    id: 'company',
                    label: selfI18n('wp_Company_Name'),
                    isrequired: true,
                    placeholder: selfI18n('wp_Please_fill_in_the_company_name'),
                    formtype: 'iselinput',
                    columns: []
                },
                {
                    id: 'address',
                    label: selfI18n('wp_Contact_address'),
                    placeholder: selfI18n('wp_Please_fill_in_the_contact_address')
                },
                {
                    id: 'email',
                    label: selfI18n('wp_E-mail'),
                    placeholder: selfI18n('wp_Please_enter_your_email'),
                    name: 'validatorEmail'
                }
            ],
            // 设备信息列设置
            equipmentprop: [
                {
                    id: 'manufacturecode',
                    label: selfI18n('wp_Factory_Number'),
                    placeholder: selfI18n('wp_Please_fill_in_the_factory_number')
                },
                {
                    id: 'model',
                    label: selfI18n('Product_model'),
                    placeholder: selfI18n('wp_Please_fill_in_the_model')
                },
                {
                    id: 'agent',
                    label: selfI18n('wp_Agent'),
                    placeholder: selfI18n('wp_Please_fill_in_the_agent_name')
                }

            ],
            // 隐私设置
            privacyprop: [
                {
                    id: 'allowviewbymanucode',
                    label: selfI18n('wp_Allow_to_query_this_repair_request_via_factory_number_of_this_equipment'),
                    isrequired: true
                }
            ],
            // 验证
            grouprules: {
                content: [
                    { required: true, message: selfI18n('wp_Please_fill_in_the_description_of_the_problem_of_your_equipment(s)') }
                ],
                name: [
                    { required: true, message: selfI18n('wp_Please_fill_in_your_name') }
                ],
                phone: [
                    { required: true, validator: validatorPhone, message: selfI18n('wp_Please_fill_in_the_correct_mobile_number') }
                ],
                company: [
                    { required: true, message: selfI18n('wp_Please_fill_in_the_company_name') }
                ],
                email: [
                    { required: false, validator: validatorEmail, message: selfI18n('wp_Please_fill_in_the_correct_email_address') }
                ],
                allowviewbymanucode: [
                    { required: true, message: selfI18n('wp_Please_choose_whether_to_allow') }
                ],
                principalphone: [
                    { validator: validatorPhone, message: selfI18n('wp_Please_fill_in_the_correct_mobile_number') }
                ]
            }
        });

        const repairForm = reactive({
            repairdata: {
                content: '',
                name: '',
                phone: '',
                company: '',
                address: '',
                email: '',
                allowviewbymanucode: false,
                manufacturecode: manucode,
                model: '',
                agent: '',
                attachments: [],
                username: Cookies.get('username') || '',
                administrator: '',
                principalphone: ''
            }
        });
        const { addNewRepair } = getRepairDataSetup();
        const { scanManufacturecodeBack, query_state } = useRepairOrderQuerySetup();
        const { archiveObj, getPrdArchDetail } = useProductArchiveDevicesSetup();
        onBeforeMount(() => {
            if (manucode) {
                const param = {
                    username: Cookies.get('username') || '',
                    manucode: repairForm.repairdata.manufacturecode
                };
                getPrdArchDetail(param, () => {
                    console.log(archiveObj);
                    repairForm.repairdata.model = archiveObj.prd_arch_detail.model;
                });
            }
        });

        const scanQrcode = () => {
            scanManufacturecodeBack((res) => {
                console.log(res);
                if (!res) {
                    showError(selfI18n('wp_Please_scan_QRcode_of_device_vendorpwd_device'));
                    return;
                }
                repairForm.repairdata.manufacturecode = query_state.manufacturecode;
                if (repairForm.repairdata.manufacturecode) {
                    const param = {
                        username: Cookies.get('username') || '',
                        manucode: repairForm.repairdata.manufacturecode
                    };
                    getPrdArchDetail(param, () => {
                        console.log(archiveObj);
                        repairForm.repairdata.model = archiveObj.prd_arch_detail.model;
                    });
                }
            });
        };

        // 获取维保负责人
        const getAllMembers = () => {
            return new Promise((resolve, reject) => {
                getAllMaintenanceTeamMembers().then((data) => {
                    state.principalprop[0].columns = state.memberList = data.value.map((item) => {
                        item.text = item.alias ? `${item.account}(${item.alias})` : item.account;
                        item.value = item.account;
                        return item;
                    });
                    resolve(data);
                });
            });
        };

        // 获取客户信息
        const getCustomerDetail = () => {
            getCustomrecordOne({
                customer_id: customer_id
            }).then((data) => {
                repairForm.repairdata.name = data.value.contactperson;
                repairForm.repairdata.phone = data.value.contactway;
                repairForm.repairdata.address = data.value.address;
                repairForm.repairdata.company = data.value.customer_name;
            });
        };

        // 获取所有客户
        const getCustomerList = () => {
            queryCustomerRecorf().then((data) => {
                state.customerList = data.value;
                state.customerprop[2].columns = data.value.map((item) => {
                    return item.customer_name;
                });
                state.customerprop[2].formtype = 'iselselect';
                state.customerprop[2].placeholder = selfI18n('wp-qing-xuan-ze-gong-si');
                state.grouprules.company[0].message = selfI18n('wp-qing-xuan-ze-gong-si');
            });
        };

        watch(() => repairForm.repairdata.administrator, (administrator, prevAdministrator) => {
            if (!prevAdministrator) return;
            const member = state.memberList.find((item) => {
                return item.account === administrator;
            });
            repairForm.repairdata.principalphone = member && member.phone;
        });

        onMounted(async () => {
            await getAllMembers();
            if (isOrdinary) {
                repairForm.repairdata.name = userinfo.name || userinfo.names;
                repairForm.repairdata.phone = userinfo.phone;
                repairForm.repairdata.address = userinfo.address;
                repairForm.repairdata.email = userinfo.email;
                repairForm.repairdata.company = userinfo.company;
            } else {
                const username = Cookies.get('username');
                repairForm.repairdata.administrator = username;
                repairForm.repairdata.principalphone = userinfo.phone;
            }
            if (customer_id) {
                getCustomerDetail();
            }
            if (!customer_id && !isOrdinary) {
                getCustomerList();
            }
        });

        return {
            ...toRefs(state),
            repairForm,
            addNewRepair,
            scanQrcode,
            validatorPhone,
            validatorEmail,
            isOrdinary,
            customer_id
        };
    },
    methods: {
        submitReport () {
            const repairform = new Promise((resolve, reject) => {
                this.$refs.repairpublicformgoup.$refs.ruleForm.validate().then(() => resolve());
            });
            const customerform = new Promise((resolve, reject) => {
                this.$refs.customerpublicformgoup.$refs.ruleForm.validate().then(() => resolve());
            });
            const deviceform = new Promise((resolve, reject) => {
                this.$refs.devicepublicformgoup.$refs.ruleForm.validate().then(() => resolve());
            });
            const principalform = new Promise((resolve, reject) => {
                this.$refs.principalpublicformgoup.$refs.ruleForm.validate().then(() => resolve());
            });
            Promise.all([repairform, customerform, deviceform, principalform]).then(() => {
                console.log(this.repairForm.repairdata);
                // 客户管理跳转时
                if (this.customer_id) {
                    this.repairForm.repairdata.customer_id = this.customer_id;
                }
                // 维保员、维保管理员登录时
                if (!this.customer_id && !this.isOrdinary) {
                    const customer = this.customerList.find(item => item.customer_name === this.repairForm.repairdata.company);
                    this.repairForm.repairdata.customer_id = customer.customer_id;
                }
                this.addNewRepair(this.repairForm.repairdata, (param) => {
                    this.$router.push({ path: '/createOrderSubmit', query: { repairId: param } });// 跳转新建成功页面
                });
            });
        },
        reportQuery () {
            this.$router.push({ path: '/repairorderquery', query: { manufacturecode: this.repairForm.repairdata.manufacturecode } });
        }
    }
};
</script>
<style lang="scss">
.repair-container{
    vertical-align: middle;
    text-align: center;
    .red{
        color: red;
    }
    .create-attachments-orderfile-container{
        display:flex;
        flex-direction:column;
        // .attach-file-upload{
        //     padding:15px 10px;
        //     margin:0;
        // }
    }
    .attachments-info-label {
        font-size: 17px;
        color: #000;
        margin: 15px 15px 5px;
        text-align: left;
    }
    .attachments-label{
        opacity: 1;
        font-size: 10px;
        font-weight: Normal;
        text-align: LEFT;
        color: rgba(0,0,0,0.60);
        line-height: 18px;
        margin: 0 15px 0px;
    }
    .content-attach-item {
        margin-left: 15px;
        margin-right: 5px;
    }
    .repair-info-container{
        margin-bottom: 5px;
        max-height: calc(100vh - 53px);
        overflow: scroll;
    }
    .button-div-fixed{
        position:fixed;
        height: 53px;
        margin: 15px 15px 0px 15px;
        bottom: 0;
        .submit-button{
            width: calc(100vw - 30px);
            height: 40px;
            margin: 7px 0px 6px;
            font-size: 18px;
            opacity: 1;
            background: #1890ff;
            border-radius: 20px;
            vertical-align: middle;
            font-weight: Normal;
            text-align: CENTER;
            color: #ffffff;
        }
    }

    .tworow-field{
        .van-cell{
            display: inline-block;
            vertical-align: middle;
            text-align: center;
        }
    }
}
.create-title-button-row{
    display: flex;
    .scan-button{
        border: none;
        color: #1890FF;
        height: 20px;
        background: #EDEDED;
        padding:0px 15px 0px 5px;
    }
}

.checkbox-cell{
    display: flex;
    justify-content: flex-start;
    height: 44px;
    align-items: center;
    // padding-top: 9px;
    // padding-bottom: 10px;
    padding: 0px 15px 0px 15px;
    .van-checkbox{
        overflow:initial;
    }
    .allowviewbymanucode-label{
        margin-left:15px;
        opacity: 1;
        font-size: 17px;
        font-weight: Normal;
        text-align: LEFT;
        color: #000000;
        line-height: 25px;
    }
}
</style>
